//
//  DiscoverViewController.m
//  TimeMovie
//
//  Created by qianfeng on 15/11/30.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "DiscoverViewController.h"

#import "newsHeadModel.h"
#import "newsTableViewModel.h"
#import "NewsOneTableViewCell.h"//新闻tableView的第一行
#import "NewsOrdinaryTableViewCell.h"

//type == 2 是带视屏图片


//导航栏按钮上的文字大小
#define fontSize [UIFont boldSystemFontOfSize:20]
//导航栏按钮文字颜色
#define navTitltColor [UIColor colorWithRed:123.0f / 255 green:193.0f / 255 blue:247.0f / 255 alpha:1]
//导航栏按钮文字选中时的颜色
#define navTitleSelectedColor [UIColor whiteColor]

//头视图上面的label字体大小
#define headLabelFondSize [UIFont boldSystemFontOfSize:25]


@interface DiscoverViewController ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>{
    UIView * sliderView;//滚动时导航栏下面跟着一起移动的小横线
    UIScrollView * _backgroundScrollView;//大的滚动视图
    UIView * navigationView;//代替的导航栏视图
    //存放头视图数据的字典
    NSMutableDictionary * _headViewDataDict;
    
    //新闻页的tableView
    UITableView * _newsTableView;
    NSMutableArray * _newsDataArray;
    
    
    int _page;//新闻的页数参数
    
    
}

@end

@implementation DiscoverViewController

- (void)viewDidLoad {
    _page = 1;
    self.navigationController.navigationBar.hidden = YES;
    [super viewDidLoad];
    //    [UIFont boldSystemFontOfSize:<#(CGFloat)#>]
    [self createNavigationButton];
    //[self news];
    [self RequestHeadViewData];
    [self RequestTableViewData];
   
    
    // Do any additional setup after loading the view.
}



/**
 定制上面的四个导航栏按钮
 */
- (void)createNavigationButton{
    
    navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screen_WIDTH, nav_Height)];
    
    //    navigationView.backgroundColor = [UIColor blackColor];
    navigationView.backgroundColor = [UIColor colorWithRed:11 / 255.0f green:95 / 255.0f blue:183 / 255.0f alpha:1];
    //打开用户交互
    navigationView.userInteractionEnabled = YES;
    //    self.navigationItem.titleView = navigationView;
    [self.view addSubview:navigationView];
    
    _backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(navigationView.frame), screen_WIDTH, screen_HEIGHT - tabBar_Height - nav_Height)];
    _backgroundScrollView.pagingEnabled = YES;
    
    
    
    _backgroundScrollView.backgroundColor = [UIColor redColor];
    _backgroundScrollView.contentSize = CGSizeMake(_backgroundScrollView.frame.size.width * 4, _backgroundScrollView.frame.size.height);
    self.automaticallyAdjustsScrollViewInsets = NO;
    _backgroundScrollView.delegate = self;
    [self.view addSubview:_backgroundScrollView];
    
    CGFloat buttonWidth = screen_WIDTH / 4.0f;
    
    NSArray * titleArray = @[@"新闻",@"预告片",@"排行榜",@"影评"];
    for (int i = 0; i < titleArray.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(buttonWidth * i, 20, buttonWidth, 42);
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.titleLabel.font = fontSize;//导航栏按钮上的文字大小
        [button addTarget:self action:@selector(navigationButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:navTitltColor forState:UIControlStateNormal];
        [button setTitleColor:navTitleSelectedColor forState:UIControlStateSelected];
        
        button.tag = 100 + i;
        [navigationView addSubview:button];
        
        if(i == 0){
            
            button.selected = YES;
            
            //根据button文字定制宽度 和 X点
            CGRect titleRect = [[button titleForState:UIControlStateNormal] boundingRectWithSize:CGSizeMake(999999, 60) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:fontSize} context:nil];
            
            
            CGFloat sliderX = (button.frame.size.width - titleRect.size.width) / 2;
            sliderView = [[UIView alloc] initWithFrame:CGRectMake(sliderX,CGRectGetMaxY(button.frame), titleRect.size.width, 2)];
            sliderView.backgroundColor = [UIColor whiteColor];
            [navigationView addSubview:sliderView];
        }
    }
    
}

#pragma mark - 请求头视图的数据
- (void)RequestHeadViewData{
    
    [self showMyAlertView];
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    [manager GET:URL_distop parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        id jsonObj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        _headViewDataDict = [NSMutableDictionary dictionaryWithDictionary:jsonObj];
        if(!_newsTableView){
            [self news];
        }
        
        //NSLog(@"DATD == %@",jsonObj);
        //NSLog(@"**** %@",_headViewDataDict);
        [self stopMyAnimation];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"ERROR == %@",error);
        [self stopMyAnimation];
        
    }];
    
    
}


#pragma mark - 请求表格数据
- (void)RequestTableViewData{
    
    // 发现 新闻 参数 type 是否MV
//#define URL_disnew @"http://api.m.mtime.cn/News/NewsList.api?pageIndex=1"
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //请求新闻页的数据
    [manager GET:[NSString stringWithFormat:URL_disnew,_page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _newsDataArray = [[NSMutableArray alloc] init];
        
        id jsonObj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary  * dict in jsonObj[@"newsList"]) {
            
            newsTableViewModel * model = [[newsTableViewModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            
            [_newsDataArray addObject:model];
            
        }
        [_newsTableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
        NSLog(@"ERROR == %@",error);
    }];
    
    
    
    
}




#pragma mark - scrollView协议方法

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int i = _backgroundScrollView.contentOffset.x / _backgroundScrollView.frame.size.width;
    //滚动停止 改变按钮的选中状态
    for (int j = 0; j < 4; j ++) {
        UIButton * button = (UIButton *)[navigationView viewWithTag:j + 100];
        if(button.tag - 100 == i){
            
            
            
            [UIView animateWithDuration:0.5f animations:^{
                [self sliderViewWidthAndXWithButton:button];
                
            } completion:^(BOOL finished) {
                button.selected = YES;
                
            }];
        }else{
            button.selected = NO;
        }
        
    }
    
}


#pragma mark - 导航栏按钮点击事件
- (void)navigationButtonClicked:(UIButton *)button{
    
    //改变按钮的选中状态
    for (int i = 0; i < 4; i ++) {
        
        UIButton * but = (UIButton *)[navigationView viewWithTag:i + 100];
        if(but.tag == button.tag){
            but.selected = YES;
            
            //下面的小横条一起移动
            [UIView animateWithDuration:0.5f animations:^{
                [self sliderViewWidthAndXWithButton:button];
                //下面的滚动试图一起滚动
                _backgroundScrollView.contentOffset = CGPointMake(i * _backgroundScrollView.contentSize.width, 0);
                
            }];
            
            
        }else{
            but.selected = NO;
        }
    }
    
}
#pragma mark - 定制下面小横线sliderView的宽度，和X

- (void)sliderViewWidthAndXWithButton:(UIButton *)button{
    
    float i = (button.tag - 100) * 1.0f;
    //下面的小横条一起移动
    
    
    //根据button文字定制宽度 和 X点
    CGRect titleRect = [[button titleForState:UIControlStateNormal] boundingRectWithSize:CGSizeMake(999999, 60) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:fontSize} context:nil];
    
    
    CGFloat sliderX = (button.frame.size.width - titleRect.size.width) / 2;
    //  NSLog(@"%f %f",i * button.frame.size.width + sliderX,i);
    sliderView.frame = CGRectMake(i * button.frame.size.width + sliderX, sliderView.frame.origin.y, titleRect.size.width, sliderView.frame.size.height);
    
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


#pragma mark - 发现
- (void)news{
    
    //创建新闻业的tableView
    _newsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _backgroundScrollView.frame.size.width, _backgroundScrollView.frame.size.height) style:UITableViewStylePlain];
    _newsTableView.delegate = self;
    _newsTableView.dataSource = self;
    _newsTableView.backgroundColor = [UIColor blackColor];
    
    
    _newsTableView.tableHeaderView = [self createHeadViewAndLabel];
    
    
    
  
   // _newsTableView.tableHeaderView = [MYCustomView createButtonWithFrame:CGRectMake(0, 0, screen_WIDTH, 250) target:self SEL:@selector(headButtonClicked:) backgoundImage:nil];
    
   // _newsTableView.tableHeaderView = [self createHeadButton];
    [_backgroundScrollView addSubview:_newsTableView];
    
    
    
    
    
    
    
    
    
    
    
    
}


#pragma mark - 创建头视图button
-(UIImageView *)createHeadViewAndLabel{
     //图片
    UIImageView * headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, screen_WIDTH, 200 * scale_Screen)];
   // if(_headViewDataDict != nil){
        
    
    newsHeadModel * newsModel = [[newsHeadModel alloc] init];
    [newsModel setValuesForKeysWithDictionary:_headViewDataDict[@"news"]];
  
    
   
    
    
    headImageView.userInteractionEnabled = YES;
    [headImageView sd_setImageWithURL:[NSURL URLWithString:newsModel.imageUrl]];
    

    
    
    //label
    UILabel * headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headImageView.frame) - 60 * scale_Screen, headImageView.frame.size.width, 60 * scale_Screen)];
    headLabel.text = newsModel.title;
    headLabel.backgroundColor = [UIColor blackColor];
    headLabel.textColor = [UIColor whiteColor];
    headLabel.textAlignment = NSTextAlignmentCenter;
    headLabel.adjustsFontSizeToFitWidth = YES;
    headLabel.font = headLabelFondSize;
    headLabel.userInteractionEnabled = YES;
    [headImageView addSubview:headLabel];
    
    //给imageView 和 label 添加点击手势
    UITapGestureRecognizer * imageTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClicked:)];
    UITapGestureRecognizer * labelTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClicked:)];
    
    
    [headImageView addGestureRecognizer:imageTapGesture];
    [headLabel addGestureRecognizer:labelTapGesture];
    //}
    
    return headImageView;
    
    
    
    
    
    /*
    newsHeadModel * newsModel = [[newsHeadModel alloc] init];
    [newsModel setValuesForKeysWithDictionary:_headViewDataDict[@"news"]];
    UIButton * button = [MYCustomView createButtonWithFrame:CGRectMake(0, 0, screen_WIDTH, 150) target:self SEL:@selector(headButtonClicked:) backgoundImage:nil];
    [button sd_setBackgroundImageWithURL:[NSURL URLWithString:newsModel.imageUrl] forState:UIControlStateNormal];
    [button setTitle:newsModel.title forState:UIControlStateNormal];
    button.titleLabel.font = headLabelFondSize;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleEdgeInsets = UIEdgeInsetsMake(button.titleLabel.frame.origin.y + 35 * scale_Screen, 0, 0, 0);
    
    button.tag = [newsModel.newsID integerValue];
    return button;
     */
}
- (void)tapClicked:(UITapGestureRecognizer *)tapGesture{
    
    NSLog(@"asd");
    
}


#pragma mark - tableView协议方法
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _newsDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row == 0){
        NewsOneTableViewCell * cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsOneTableViewCell" owner:nil options:nil] lastObject];
        return cell;
        
    }else{
        
    static NSString * ordinaryID = @"ordinary";
    NewsOrdinaryTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ordinaryID];
    if(cell == nil){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsOrdinaryTableViewCell" owner:nil options:nil] lastObject];
    }
    cell.model = _newsDataArray[indexPath.row - 1];
        
        
        
        
    return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 0){
        return 60 * scale_Screen;
    }else{
        return 120.0f * scale_Screen;
    }
    
}

@end





































